<template>
  <!-- 
  今日进度:

  展开的tag添加删除 未完成

 -->
  <div class="params">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert style="margin-bottom: 15px;" title="注意: 只允许为第三级分类设置相关参数!" :closable="false" type="warning" show-icon>
      </el-alert>
      <span>选择商品分类: </span>
      <el-cascader clearable v-model="choice" :options="selectoptions" :props="selectprop" @change="handleChange">
      </el-cascader>
      <!-- tabs  -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数 -->
          <el-button @click="add_btn" :disabled="choice == false" size="mini" type="primary">添加参数</el-button>
          <!-- 表格 -->
          <el-table v-if="activeName === 'many'" :data="tableData1" :border="true" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <!-- {{ props.row.attr_vals ? props.row.attr_vals.split(',').length : [] }} -->
                <el-tag v-for="(tag, index) in props.row.attr_vals" :key="'tag' + index" closable
                  :disable-transitions="true" @close="handleClose(props.row.attr_vals, tag, props.row)"
                  :style="[{ marginLeft: 25 + 'px' }]">
                  {{ tag }}
                </el-tag>
                <el-input style="margin-left: 25px;width: 100px;" class="input-new-tag" v-if="props.row.inputVisible"
                  v-model="props.row.taginput" ref="taginput" size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)" @blur="handleInputConfirm(props.row)">
                </el-input>
                <el-button style="margin-left: 25px;" v-else class="button-new-tag" size="small"
                  @click="tagbtn(props.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="setbtn(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑
                </el-button>
                <el-button @click="delete_btn(scope.row)" size="mini" type="danger" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button @click="add_btn" :disabled="choice == false" size="mini" type="primary">
            添加属性</el-button>
          <el-table v-if="activeName === 'only'" :data="tableData2" :border="true" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <!-- {{ props.row.attr_vals ? props.row.attr_vals.split(',').length : [] }} -->
                <el-tag v-for="(tag, index) in props.row.attr_vals" :key="'tag' + index" closable
                  :disable-transitions="true" @close="handleClose(props.row.attr_vals, tag, props.row)"
                  :style="[{ marginLeft: 25 + 'px' }]">
                  {{ tag }}
                </el-tag>
                <el-input style="margin-left: 25px;width: 100px;" class="input-new-tag" v-if="props.row.inputVisible"
                  v-model="props.row.taginput" ref="taginput" size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)" @blur="handleInputConfirm(props.row)">
                </el-input>
                <el-button style="margin-left: 25px;" v-else class="button-new-tag" size="small"
                  @click="tagbtn(props.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="setbtn(scope.row)" size="mini" type="primary" icon="el-icon-edit">编辑
                </el-button>
                <el-button @click="delete_btn(scope.row)" size="mini" type="danger" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加 -->
    <el-dialog :title="'添加' + activeName == 'many' ? '动态参数' : '静态属性'" @close="add_close" :visible.sync="add_dialog"
      width="50%">
      <el-form ref="add_ref" label-width="90px" :model="add_from" :rules="add_rules">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性' + ' :'" prop="attr_name">
          <el-input v-model="add_from.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="add_dialog = false">取 消</el-button>
        <el-button type="primary" @click="add_dialog_ok">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog :title="'修改' + activeName == 'many' ? '动态参数' : '静态属性'" @close="set_close" :visible.sync="set_dialog"
      width="50%">
      <el-form ref="set_ref" label-width="90px" :model="set_from" :rules="set_rules">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性' + ' :'" prop="attr_name">
          <el-input v-model="set_from.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="set_dialog = false">取 消</el-button>
        <el-button type="primary" @click="set_dialog_ok">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //select
      choice: [],
      selectoptions: [],
      selectprop: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
      },
      //tabs
      activeName: 'many',
      //表格数据
      tableData1: [],
      inputVisible: false,
      taginput: '',
      tableData2: [],
      /*
        添加
      */
      add_dialog: false,
      add_from: {
        attr_name: '',
      },
      add_rules: {
        attr_name: [
          { required: true, message: '请输入动态参数', trigger: 'blur' },
        ],
      },
      /*
        修改
      */
      set_dialog: false,
      set_from: {
        attr_name: '',
      },
      set_rules: {
        attr_name: [
          { required: true, message: '请输入动态参数', trigger: 'blur' },
        ]
      }

    }
  },
  created() {
    this.initselect();
  },
  methods: {
    async initselect() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.selectoptions = res.data
    },
    //select值改变
    async handleChange() {
      if (this.choice.length == 0) {
        this.tableData1 = this.tableData2 = []
        return
      }
      let { data: res } = await this.$http.get(`categories/${this.choice[this.choice.length - 1]}/attributes`, { params: { sel: this.activeName } });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      //过滤标签变成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false;
        item.taginput = '';
      });
      if (this.activeName == 'many') this.tableData1 = res.data;
      else this.tableData2 = res.data;
      console.log(res.data);
    },
    //tabs
    handleClick() {
      if (this.choice != false) {
        this.handleChange();
      }
    },
    //表格下的tag
    //关闭tag
    async handleClose(list, tag, row) {
      //当前点击的索引
      let listindex = list.indexOf(tag)
      //删除这个索引的新数组
      let newlist = list
      newlist.splice(listindex, 1);
      //用空格分割成字符串
      let newstr = newlist.join(' ')
      //提交
      let id = row.attr_id
      let info = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: newstr
      }
      let { data: res } = await this.$http.put(`categories/${this.choice[this.choice.length - 1]}/attributes/${id}`, info);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      row = res.data
    },

    //确定添加tag
    async handleInputConfirm(row) {
      if (!row.taginput) {
        row.inputVisible = false;
        return this.$message.error('取消操作');
      }
      let oldlist = [...row.attr_vals];
      oldlist.push(row.taginput);
      //添加
      let newstr = oldlist.join(' ');
      let info = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: newstr
      };
      let id = row.cat_id;
      let attrId = row.attr_id;
      let { data: res } = await this.$http.put(`categories/${id}/attributes/${attrId}`, info);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      row.attr_vals = oldlist
      row.taginput = '';
      row.inputVisible = false;

    },
    tagbtn(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.taginput.$refs.input.focus()
      })
    },
    /*
      添加
    */

    //添加按钮
    add_btn() {
      this.add_dialog = true;
    },
    //弹框关闭事件
    add_close() {
      this.add_from = {
        attr_name: '',
      }
    },
    //确定按钮
    add_dialog_ok() {
      this.$refs.add_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        //整合数据
        let info = {
          attr_name: this.add_from.attr_name,
          attr_sel: this.activeName,
        }
        let { data: res } = await this.$http.post(`categories/${this.choice[this.choice.length - 1]}/attributes`, info);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success('创建成功');
        this.handleChange()
        this.add_dialog = false;
      })
    },
    /*
      修改
    */

    //确定
    set_dialog_ok() {
      this.$refs.set_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        //整合数据
        let info = {
          attr_name: this.set_from.attr_name,
          attr_sel: this.activeName,
        }
        let { data: res } = await this.$http.put(`categories/${this.choice[this.choice.length - 1]}/attributes/${this.set_from.attr_id}`, info);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success('修改成功');
        this.handleChange()
        this.set_dialog = false;
      })
    },
    //弹框消失
    set_close() {
      this.set_from = {
        attr_name: '',
      };
    },
    //修改按钮
    setbtn(row) {
      this.deepcopy(this.set_from, row);
      this.set_dialog = true;
    },
    //深拷贝
    deepcopy(copy, obj) {
      //获取属性 判断是数组?是对象?还是简单数据类型
      for (let k in obj) {
        if (obj[k] instanceof Array) {
          copy[k] = [];
          this.deepcopy(copy[k], obj[k]);
        } else if (obj[k] instanceof Object) {
          copy[k] = {};
          this.deepcopy(copy[k], obj[k]);
        } else {
          copy[k] = obj[k];
        }
      }
    },
    /*
      删除
    */
    delete_btn(row) {
      let id = row.attr_id
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //删除操作
        let { data: res } = await this.$http.delete(`categories/${this.choice[this.choice.length - 1]}/attributes/${id}`);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.handleChange()
        this.$message.success('删除成功');
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
  },
}
</script>

<style>
</style>